package com.sixbro.gateway.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sixbro.common.domain.ApiResponse;
import com.sixbro.common.domain.ApiResponseCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.handler.ResponseStatusExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * <p>
 *  网关异常通用处理器，只作用在webflux 环境下 , 优先级低于 {@link ResponseStatusExceptionHandler} 执行
 *  {@link DefaultErrorWebExceptionHandler }
 *  {@link DefaultErrorAttributes }
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/16 14:23
 */
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 设置返回JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ApiResponseCode apiResponseCode = ApiResponseCode.FAILURE;
        if (ex instanceof InvalidBearerTokenException) {
            apiResponseCode = ApiResponseCode.TOKEN_INVALID_OR_EXPIRED;
        }

        ApiResponseCode finalApiResponseCode = apiResponseCode;
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                // 返回响应结果
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(ApiResponse.failed(finalApiResponseCode).setUri(request.getURI().toString())));
            } catch (JsonProcessingException e) {
                log.warn("error writing response", ex);
                e.printStackTrace();
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
